import 'package:flutter/foundation.dart';
import 'sqlite_util.dart';

class MainManager with ChangeNotifier {
  static MainManager instance = MainManager();

  List allLuckyGuys = [];
  final sqliteUtil = SqliteUtil();

  void init() async {
    sqliteUtil.createDb(1);
    // clearDb();
    refreshDbList();
  }

  Future queryAll() async {
    return query("select * from luckyguy");
  }

  void clearDb() {
    sqliteUtil.delete("DELETE FROM luckyguy");
  }

  Future query(sql) async {
    return sqliteUtil.query(sql);
  }

  void insert(luckyguys) async {
    var data = luckyguys.join('|');
    await sqliteUtil
        .insert('INSERT INTO luckyguy(id,luckyguys) VALUES(0,"$data")');
    refreshDbList();
  }

  void update(luckyguys) async {
    await sqliteUtil.update('UPDATE luckyguy SET luckyguys = ? WHERE id = 0',
        [luckyguys.join('|')]);
    refreshDbList();
  }

  void delete(luckyguys) async {
    await sqliteUtil
        .delete('DELETE FROM luckyguy WHERE id = ${luckyguys['id']}');
    refreshDbList();
  }

  refreshDbList() {
    queryAll().then((res) {
      if (res.length == 0) {
        allLuckyGuys = ['张三', '李四', '王二'];
        insert(allLuckyGuys);
        notifyListeners();
      } else {
        allLuckyGuys = res[0]['luckyguys'].split('|');
        notifyListeners();
      }
    });
  }
}
